﻿using Apewer;
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;

namespace Apewer.Network
{

    internal class MailMethods
    {

        public static MailRecord Send(MailClient client, MailMessage message)
        {
            var record = new MailRecord();
            record.Action = "Send";
            record.Client = Json.From(client == null ? new MailClient() : client).ToString();
            record.Message = (message == null ? new MailMessage() : message).ToJson().ToString();

            var smtp = null as System.Net.Mail.SmtpClient;
            var mail = null as System.Net.Mail.MailMessage;
            try
            {
                smtp = client.ToInstance();
                mail = message.ToInstance();
                smtp.Send(mail);

                record.Status = "Ok";
            }
            catch (Exception ex)
            {
                record.Status = "Exception";
                record.Exception = ex;
                record.Error = ex.ToString();
            }
            if (smtp != null)
            {
#if !NET20
                smtp.Dispose();
#endif
            }
            if (mail != null) mail.Dispose();

            return record;
        }

        public static MailRecord Send(MailClient client, string sender, string receiver, string content, string title)
        {
            var message = new MailMessage();
            message.Sender = new MailAddress(sender);
            message.Receiver.Add(new MailAddress(receiver));
            message.Content = content;
            message.Title = title;

            return Send(client, message);
        }

    }

}
